﻿ IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'ContactoSave')
	BEGIN
		DROP  Procedure  ContactoSave
	END
GO

CREATE PROCEDURE ContactoSave
	(	
		@id						AS INT,
		@nombre					AS VARCHAR(50),
		@empresaId				AS INT,
		@tipo					AS CHAR(1),
		@referencia				AS INT,
		@puesto					AS VARCHAR(50),		
		@email					AS VARCHAR(200),
		@telefono				AS VARCHAR(30),		
		@celular				AS VARCHAR(30),
		@notas					AS VARCHAR(500),		
		@user					AS VARCHAR(30)
	)	
AS
BEGIN	
	SET NOCOUNT ON
	
	DECLARE @currentDate AS DATETIME
	SET @currentDate = GETDATE()
	
	IF EXISTS(SELECT 1 FROM Contacto WHERE ContactoId = @id)
	BEGIN
		UPDATE Contacto
		SET Nombre = @nombre,
			Tipo = @tipo,
			Referencia = @referencia,
			Puesto = @puesto,
			Email = @email,
			Telefono =  @telefono,
			Celular =  @celular,
			Notas =  @notas,
			Activo = 1,
			FechaModificacion = @currentDate,
			ModificadoPor = @user		
		WHERE ContactoId = @id
	END
	ELSE
	BEGIN	
		SELECT @id = ISNULL(MAX(ContactoId),0)+1 FROM Contacto

		INSERT INTO Contacto
			(ContactoId, Nombre, Tipo, Referencia, Puesto, Email, Telefono, Celular, Notas,			
			Activo, FechaCreacion, FechaModificacion, ModificadoPor, EmpresaId)
		VALUES
			(@id, @nombre, @tipo, @referencia, @puesto, @email, @telefono, @celular, @notas,
			1, @currentDate, @currentDate, @user, @empresaId)	
	END
	
	
	SET NOCOUNT OFF
END  